<template>
  <el-container style="flex-direction: column; height: 100vh; background: linear-gradient(135deg, #f8f9fa, #e9ecef);">
    <!-- 返回按钮 -->
    <el-button type="primary" icon="el-icon-back" @click="goToHome" class="back-button" circle>
    </el-button>

    <!-- 个人中心主卡片 -->
    <el-card class="personal-card">
      <!-- 用户信息区 -->
      <div class="user-profile">
        <div class="avatar-section">
          <el-avatar :size="120" :src="userInfo.image" class="user-avatar"></el-avatar>
          <el-upload class="avatar-upload" action="/api/upload" :show-file-list="false"
            :before-upload="beforeAvatarUpload" :on-success="handleAvatarSuccess">
            <el-button size="small" type="primary">更换头像</el-button>
          </el-upload>
        </div>
        <div class="profile-info">
          <h2 class="username">{{ userInfo.username }}</h2>
          <div class="meta-info">
            <div class="meta-item">
              <i class="el-icon-message"></i>
              <span>{{ userInfo.email }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-mobile-phone"></i>
              <span>{{ userInfo.phone || '未绑定手机' }}</span>
            </div>
            <div class="meta-item">
              <i class="el-icon-date"></i>
              <span>注册时间：{{ formatDate(userInfo.createTime) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 数据看板 -->
      <div class="dashboard">
        <el-card class="stat-card" v-for="(stat, index) in stats" :key="index">
          <div class="stat-icon" :class="`type-${index}`">
            <i :class="stat.icon"></i>
          </div>
          <h3>{{ stat.title }}</h3>
          <p class="stat-value">{{ stat.value }}</p>
        </el-card>
      </div>

      <!-- 功能标签页 -->
      <el-tabs v-model="activeTab" class="function-tabs">
        <!-- 个人信息标签页 -->
        <el-tab-pane label="个人信息" name="profile">
          <el-form :model="userInfo" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="userInfo.username" disabled></el-input>
            </el-form-item>
            <el-form-item label="真实姓名">
              <el-input v-model="userInfo.realName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item label="联系电话">
              <el-input v-model="userInfo.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
            <el-form-item label="电子邮箱">
              <el-input v-model="userInfo.email" placeholder="请输入邮箱地址"></el-input>
            </el-form-item>
            <el-button type="primary" @click="updateProfile">保存修改</el-button>
          </el-form>
        </el-tab-pane>

        <!-- 安全设置标签页 -->
        <el-tab-pane label="安全设置" name="security">
          <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input type="password" v-model="passwordForm.oldPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="newPassword">
              <el-input type="password" v-model="passwordForm.newPassword" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input type="password" v-model="passwordForm.confirmPassword" show-password></el-input>
            </el-form-item>
            <el-button type="primary" @click="submitPasswordForm">修改密码</el-button>
          </el-form>
        </el-tab-pane>
      </el-tabs>

      <!-- 投诉建议按钮 -->
      <el-button type="warning" icon="el-icon-warning" class="feedback-btn" @click="openFeedbackDialog">
        意见反馈
      </el-button>
    </el-card>

    <!-- 反馈对话框 -->
    <el-dialog title="意见反馈" :visible.sync="showFeedbackDialog" width="600px" custom-class="feedback-dialog">
      <el-form :model="feedbackForm">
        <el-form-item label="反馈类型" prop="type">
          <el-select v-model="feedbackForm.type" placeholder="请选择反馈类型">
            <el-option label="功能建议" value="feature"></el-option>
            <el-option label="问题反馈" value="bug"></el-option>
            <el-option label="投诉建议" value="complaint"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="反馈内容" prop="content">
          <el-input type="textarea" :rows="5" v-model="feedbackForm.content" placeholder="请详细描述您的反馈内容" maxlength="500"
            show-word-limit>
          </el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="showFeedbackDialog = false">取消</el-button>
        <el-button type="primary" @click="submitFeedback">提交反馈</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  name: 'UserProfile',
  data() {
    const validatePassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'));
      } else if (value.length < 8) {
        callback(new Error('密码长度不能少于8位'));
      } else if (!/[A-Z]/.test(value)) {
        callback(new Error('必须包含大写字母'));
      } else if (!/\d/.test(value)) {
        callback(new Error('必须包含数字'));
      } else {
        callback();
      }
    };

    return {
      userInfo: {},
      activeTab: 'profile',
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      passwordRules: {
        oldPassword: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        newPassword: [{ required: true, validator: validatePassword, trigger: 'blur' }],
        confirmPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.passwordForm.newPassword) {
                callback(new Error('两次输入密码不一致'));
              } else {
                callback();
              }
            }, trigger: 'blur'
          }
        ]
      },
      showFeedbackDialog: false,
      feedbackForm: {
        type: 'feature',
        content: ''
      },
      stats: [
        { icon: 'el-icon-user', title: '社区活跃度', value: '' },
        { icon: 'el-icon-medal', title: '贡献积分', value: '' },
        { icon: 'el-icon-data-line', title: '本周活跃', value: '' },
        { icon: 'el-icon-collection', title: '点赞次数', value: '' }
      ]
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      service.get(`/api/user/getUserInfo/${this.userInfo.id}`).then(result => {
        result = result.data
        if (result.code == 1) {
          this.userInfo = result.data;
          console.log(this.userInfo);
          this.stats[0].value = `Lv.${Math.ceil(this.userInfo.level / 100)}`;
          this.stats[1].value = this.userInfo.contribution;
          this.stats[2].value = this.userInfo.active;
          this.stats[3].value = this.userInfo.likeNum;
        } else {
          this.$message.error(result.msg);
        }
      }).catch(error => {
        this.$message.error('获取用户信息失败');
        console.error(error);
      });
    },

    formatDate(timestamp) {
      return new Date(timestamp).toLocaleDateString();
    },

    async updateProfile() {
      try {
        await service.put('/users/profile', this.userInfo);
        this.$message.success('资料更新成功');
      } catch (error) {
        this.$message.error('资料更新失败');
      }
    },

    handleAvatarSuccess(res) {
      this.userInfo.image = res.data.url;
      this.$message.success('头像更新成功');
    },

    beforeAvatarUpload(file) {
      const isImage = ['image/jpeg', 'image/png'].includes(file.type);
      const isUnder2M = file.size / 1024 / 1024 < 2;

      if (!isImage) this.$message.error('仅支持JPG/PNG格式');
      if (!isUnder2M) this.$message.error('图片大小不能超过2MB');
      return isImage && isUnder2M;
    },

    submitPasswordForm() {
      this.$refs.passwordForm.validate(async valid => {
        if (valid) {
          try {
            await service.post('/auth/change-password', this.passwordForm);
            this.$message.success('密码修改成功');
            this.passwordForm = { oldPassword: '', newPassword: '', confirmPassword: '' };
          } catch (error) {
            this.$message.error(error.response?.data?.message || '密码修改失败');
          }
        }
      });
    },

    openFeedbackDialog() {
      this.showFeedbackDialog = true;
    },

    async submitFeedback() {
      if (!this.feedbackForm.content.trim()) {
        this.$message.warning('请填写反馈内容');
        return;
      }

      try {
        await service.post('/feedback', this.feedbackForm);
        this.$message.success('反馈提交成功');
        this.showFeedbackDialog = false;
        this.feedbackForm = { type: 'feature', content: '' };
      } catch (error) {
        this.$message.error('反馈提交失败');
      }
    },

    goToHome() {
      this.$router.push('/owner/home');
    }
  }
};
</script>

<style scoped>
.back-button {
  position: fixed;
  top: 24px;
  left: 24px;
  z-index: 1000;
  width: 48px;
  height: 48px;
  font-size: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.back-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.personal-card {
  width: 80%;
  max-width: 1000px;
  margin: 80px auto;
  margin-top: 10px;
  margin-bottom: 10px;
  border-radius: 16px;
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.08);
  height: 100vh;
  /* 设置固定高度 */
  overflow-y: auto;
  /* 添加垂直滚动条 */
}

.user-profile {
  display: flex;
  align-items: flex-start;
  gap: 40px;
  padding: 32px;
  border-bottom: 1px solid #eee;
}

.avatar-section {
  text-align: center;
  flex-shrink: 0;
}

.user-avatar {
  margin-bottom: 16px;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.profile-info {
  flex: 1;
}

.username {
  margin: 0 0 12px;
  font-size: 28px;
  color: #1a1a1a;
}

.meta-info {
  display: grid;
  gap: 12px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #666;
  font-size: 16px;
}

.meta-item i {
  font-size: 18px;
  color: #409EFF;
}

.dashboard {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  padding: 24px;
}

.stat-card {
  text-align: center;
  transition: transform 0.3s ease;
  border: none;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  margin: 0 auto 16px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: white;
}

.stat-icon.type-0 {
  background: #409EFF;
}

.stat-icon.type-1 {
  background: #67C23A;
}

.stat-icon.type-2 {
  background: #E6A23C;
}

.stat-icon.type-3 {
  background: #F56C6C;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  margin: 8px 0;
}

.function-tabs {
  margin: 10px;
}

.function-tabs>>>.el-tabs__nav-wrap::after {
  height: 1px;
  background: #eee;
}

.function-tabs>>>.el-tabs__item {
  font-size: 16px;
  padding: 0 24px;
}

.feedback-btn {
  width: calc(100% - 48px);
  margin: 24px;
  height: 48px;
  font-size: 16px;
  border-radius: 8px;
}

.feedback-dialog>>>.el-dialog__body {
  padding: 24px;
}

@media (max-width: 768px) {
  .user-profile {
    flex-direction: column;
    align-items: center;
    text-align: center;
  }

  .dashboard {
    grid-template-columns: 1fr;
  }

  .personal-card {
    margin: 60px 16px;
    width: auto;
  }
}
</style>